package com.intelligentpension.utils

import androidx.appcompat.app.AppCompatActivity
import com.afollestad.materialdialogs.MaterialDialog
import com.intelligentpension.kotlinwifi.R
import com.permissionx.guolindev.PermissionX


/**
 * 版权：点赞 版权所有
 * author :赵航
 * @e-mail: zhaohangcn@gmail.com
 * time：2022/4/9
 * describe ：
 */
class PermissionUtil {

    //权限组，用户授权了某个权限，同一个权限组里面的其他权限也会自动授予权限。
    //这里每组选择一个权限，如果这个规则改变了，就要授权具体的权限。
    val CALENDAR = "android.permission.READ_CALENDAR" //日历

    val CAMERA = "android.permission.CAMERA" //相机

    val CONTACTS = "android.permission.READ_CONTACTS" //通讯录

    val LOCATION = "android.permission.ACCESS_FINE_LOCATION" //定位

    val RECORD_AUDIO = "android.permission.RECORD_AUDIO" //麦克风

    val PHONE = "android.permission.CALL_PHONE" //电话

    val SENSORS = "android.permission.BODY_SENSORS" //传感器

    val SMS = "android.permission.READ_SMS" //短信

    val STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE" //存储


    //用户禁止授权的默认提示语
    private val SHOW_AGAIN_MESSAGE = "您拒绝了授权，无法正常使用"

    //用户禁止授权并且勾选了不再询问的默认提示语
    private val NOT_SHOW_AGAIN_MESSAGE = "您禁止了授权，请在手机设置里面授权"


    /**对外暴露权限请求的结果
     *  onSuccessd请求成功
     *  onFailed 请求失败,其中showAgain表示,是否不在询问
     */
    interface OnPermissionListener {
        fun onSuccessd()
        fun onFailed()
    }

    //单个权限的请求
    fun requestSingle(
        activity: AppCompatActivity,
        showAgainMsg: Int,
        listener: OnPermissionListener?,
        permission: String
    ) {
        PermissionX.init(activity).permissions(permission)
            .request { allGranted: Boolean, _: List<String>?, _: List<String>? ->
                if (allGranted) {
                    listener?.onSuccessd()
                } else {
                    listener?.onFailed()
                    var materialDialog = MaterialDialog(activity)
                    materialDialog.show {
                        message(showAgainMsg)
                        positiveButton(text = "确定")
                        negativeButton(text = "取消")
                        cancelOnTouchOutside(false)
                        positiveButton {

                        }
                        negativeButton {

                        }

                    }
                }
            }

    }

    //权限组
    fun requestMultiple(
        activity: AppCompatActivity,
        showAgainMsg: String,
        listener: OnPermissionListener?,
        permissionList: List<String>
    ) {
        PermissionX.init(activity).permissions(permissionList)
            .request { allGranted: Boolean, _: List<String?>?, _: List<String?> ->
                if (allGranted) {
                    //  Toast.makeText(activity, "所有申请的权限都已通过", Toast.LENGTH_LONG).show()
                    listener?.onSuccessd()
                } else {
                    listener?.onFailed()
                    // Toast.makeText(activity, "您拒绝了如下权限：$deniedList", Toast.LENGTH_LONG).show()
                }
            }
    }
}